import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:interview/components/page/page_empty.dart';
import 'package:interview/components/page/page_list_custom.dart';
import 'package:interview/components/page/page_load.dart';
import 'package:interview/components/question/question_item.dart';
import 'package:interview/controller/question_controller.dart';
import 'package:interview/providers/app_refresh_providers.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class QuestionList extends StatefulWidget {
  final int? typeId;
  final int? sort;
  final String? keyword;
  const QuestionList({
    super.key, 
    this.typeId, 
    this.sort,
    this.keyword
  });

  @override
  State<QuestionList> createState() => _QuestionListState();
}


/* 
使用 AutomaticKeepAliveClientMixin 缓存页面
通过 AutomaticKeepAliveClientMixin，可以让每个 QuestionList 在切换时保留状态，避免销毁和重复请求。
*/
class _QuestionListState extends State<QuestionList> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true; // 保持页面状态
  final RefreshController _refreshController = RefreshController(initialRefresh: false);
  final QuestionController _questionController = Get.put(QuestionController());
  late QuestionPageState _pageState;

  // 监听父组件的状态
  @override
  void didUpdateWidget(covariant QuestionList oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 检测父组件传递的 sort 是否发生了变化
    if (oldWidget.sort != widget.sort) {
      _onRefresh(); // 如果变化，执行刷新逻辑
    }
    // 检测父组件传递的 keyword
    if (oldWidget.keyword != widget.keyword) {
      _onRefresh(); // 如果变化，执行刷新逻辑
    }
  }

  Future <void> _onRefresh() async {
    _refreshController.resetNoData(); // 这里重置状态
    if (widget.keyword != null){
      await _questionController.refreshQuestions( context: context,keyword: widget.keyword);
    }else{
      await _questionController.refreshQuestions( context: context,typeId: widget.typeId!,sort: widget.sort!);
    }
    
    _refreshController.refreshCompleted();
  }

  Future <void> _onLoading() async {
    if (widget.keyword != null){
      await _questionController.loadMoreQuestions( context: context,keyword: widget.keyword);
    }else{
      await _questionController.loadMoreQuestions(context: context, typeId: widget.typeId!, sort: widget.sort!);
    }
    if (_pageState.isFinished.value) {
      _refreshController.loadNoData();
    } else {
      _refreshController.loadComplete();
    }
  }

  @override
  void initState() {
    super.initState();
   // 根据传入参数决定数据初始化方式
    if (widget.keyword != null) {
      _pageState = _questionController.getKeywordPageState(widget.keyword!);
    } else {
      _pageState = _questionController.getPageState(widget.typeId!);
    }
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _onLoading();
    });
  }
  
  @override
  Widget build(BuildContext context) {
    super.build(context); // 确保 AutomaticKeepAliveClientMixin 生效
    return Consumer<AppRefreshProvider>(
      builder: (context, refreshNotifier , child){
        if(refreshNotifier.shouldRefresh && mounted){
          // 延迟执行数据加载，避免在构建过程中直接调用
          WidgetsBinding.instance.addPostFrameCallback((_) {
            _onLoading().then((_){
              refreshNotifier.resetRefresh(); // 重置刷新标志
            });
          });
        }
        return Obx((){
          final questionList = _pageState.questionList;
          return SmartRefresher(
            controller: _refreshController,
            enablePullDown: true,
            enablePullUp: true,
            header: const ListCustomHeader(),
            footer:const ListCustomFooter(),
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            child: questionList.isEmpty?(_pageState.isFinished.value ? const PageEmpty(): const PageLoad(width: 2)):
            ListView.separated(
              itemCount: questionList.length,
              itemBuilder: (context,index) {
                final quesListItem = questionList[index];
                return QuestionItem(
                  ids:questionList.map((e) => e.id).toList(),
                  id:quesListItem.id,
                  typeId:widget.typeId ?? 0,
                  difficulty: quesListItem.difficulty,
                  title:quesListItem.stem,
                  likes: quesListItem.likeCount.value,
                  views: quesListItem.views.value,
                  isViewed: quesListItem.readFlag == 1,
                );
              },
              separatorBuilder: (context, index) {
                return const Divider(
                  color: Color.fromARGB(255, 231, 231, 231), // 分割线颜色
                  height: 0.5, // 分割线高度
                  thickness: 0.5, // 分割线粗细
                  indent: 16, // 左侧缩进
                  endIndent: 16, // 右侧缩进
                );
              },
            ),
          );
        });
      },
    );
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }
}

